/*
 * Unidata Platform
 * Copyright (c) 2013-2020, UNIDATA LLC, All rights reserved.
 *
 * Commercial License
 * This version of Unidata Platform is licensed commercially and is the appropriate option for the vast majority of use cases.
 *
 * Please see the Unidata Licensing page at: https://unidata-platform.com/license/
 * For clarification or additional options, please contact: info@unidata-platform.com
 * -------
 * Disclaimer:
 * -------
 * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
 * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
 * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
 * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
 * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
 */
package org.unidata.mdm.rest.meta.service;

import java.util.Objects;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.annotation.Autowired;
import org.unidata.mdm.core.service.MetaModelService;
import org.unidata.mdm.meta.context.GetDataModelContext;
import org.unidata.mdm.meta.context.UpsertDataModelContext;
import org.unidata.mdm.meta.dto.GetEntitiesGroupsDTO;
import org.unidata.mdm.meta.dto.GetModelDTO;
import org.unidata.mdm.rest.meta.converter.EntitiesGroupConverter;
import org.unidata.mdm.rest.meta.ro.FilledEntityGroupMappingRO;
import org.unidata.mdm.rest.system.ro.ErrorResponse;
import org.unidata.mdm.rest.system.ro.RestResponse;
import org.unidata.mdm.rest.system.service.AbstractRestService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;

/**
 * Group rest service
 */
@Path(EntitiesGroupRestService.SERVICE_PATH)
@Consumes({"application/json"})
@Produces({"application/json"})
public class EntitiesGroupRestService extends AbstractRestService {
    /**
     * This service path.
     */
    public static final String SERVICE_PATH = "entities-group";
    /**
     * The metamodel service.
     */
    @Autowired
    private MetaModelService metaModelService;
    /**
     * Load and return list of all entities group
     *
     * @return list of source systems. {@see FlatGroupMapping}.
     */
    @GET
    @Operation(
        description = "Return all entity groups, starting from the root.",
        method = HttpMethod.GET,
        responses = {
            @ApiResponse(content = @Content(schema = @Schema(implementation = RestResponse.class)), responseCode = "200"),
            @ApiResponse(content = @Content(schema = @Schema(implementation = ErrorResponse.class)), responseCode = "500")
        }
    )
    public Response findAll(
            @Parameter(description = "Return only filled groups, if true.", in = ParameterIn.QUERY) @QueryParam("filled") @DefaultValue("false") boolean filled,
            @Parameter(description = "Draft id for draft version.", in = ParameterIn.QUERY) @QueryParam("draftId") @DefaultValue("0") long draftId ) {

        GetModelDTO result = metaModelService.get(GetDataModelContext.builder()
                .allEntityGroups(true)
                .draftId(draftId > 0 ? draftId : null)
                .build());

        GetEntitiesGroupsDTO groups = Objects.nonNull(result) ? result.getEntityGroups() : null;
    	return ok(new RestResponse<>(filled ? EntitiesGroupConverter.toFilled(groups) : EntitiesGroupConverter.toFlat(groups)));
    }
    /**
     * Updates entities group.
     *
     * @param ro all necessary info about group.
     * @return 200 Ok
     */
    @PUT
    @Operation(
        description = "Upsert an entities group.",
        method = HttpMethod.PUT,
        requestBody = @RequestBody(content = @Content(schema = @Schema(implementation = FilledEntityGroupMappingRO.class)), description = "The update"),
        responses = {
            @ApiResponse(content = @Content(schema = @Schema(implementation = RestResponse.class)), responseCode = "200"),
            @ApiResponse(content = @Content(schema = @Schema(implementation = ErrorResponse.class)), responseCode = "500")
        }
    )
    public Response update(FilledEntityGroupMappingRO ro,
            @Parameter(description = "The draft id for drafts. Optional.", in = ParameterIn.QUERY) @QueryParam("draftId") @DefaultValue("0") long draftId ) {

        metaModelService.upsert(UpsertDataModelContext.builder()
                .entitiesGroupsUpdate(EntitiesGroupConverter.from(ro))
                .draftId(draftId > 0 ? draftId : null)
                .build());

        return ok(new RestResponse<>());
    }
}
